package com.heima.wemedia.service.iml;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import io.jsonwebtoken.lang.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.amqp.core.MessagePostProcessor;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;
    //删除文章和素材之间关联关系
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
   @Autowired
    RabbitTemplate rabbitTemplate;

    /*
    * 分页带条件查询自媒体文章列表
    * */
    @Override
    public ResponseResult<WmNews> findNewsByPage(WmNewsPageReqDTO dto) {
        //1.校验参数
        dto.checkParam();
       //2.查询条件
        Page<WmNews> pagepeq = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
          //2.1如果有文章标题，按照文章标题模糊查询
         if(StringUtils.isNotBlank(dto.getKeyword())){
             wrapper.like(WmNews::getTitle,dto.getKeyword());
         }
          //2.2如果有频道信息，按照频道id查询
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
          //2.3如果有文章状态，按照状态信息进行查询
           if (dto.getStatus() != null){
               wrapper.eq(WmNews::getStatus,dto.getStatus());
           }
          //2.4开始时间和结束时间不为空，按照时间区间查询
          if (dto.getBeginPubDate() != null || dto.getEndPubDate()!= null){
              wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
          }
          //2.5按照登录用户id查询
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
          if (wmUser == null){
              return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
          }
          wrapper.eq(WmNews::getUserId,wmUser.getId());
        //2.2按照创建时间降序
          wrapper.orderByDesc(WmNews::getCreatedTime);
        //3。分页查询
        IPage<WmNews> pageResult = this.page(pagepeq, wrapper);
        //4。返回结果,封装结果，前端已经固定了文件图片前缀
       PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }

    /*
     * 保存或修改、发布文章
     * */
    @Transactional

    @Override
    public ResponseResult<WmNews> saveOrUpdate(WmNewsDTO wmNewsDTO) {
        //1.检验参数，，自动生成封面的将type属性设置为null，images属性数据改为字符串类型
        if (wmNewsDTO ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        //文本内容不能为空
         if (StringUtils.isBlank(wmNewsDTO.getContent())){
             return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章文本内容不能为空");
         }
           //1.1用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
        if (wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE,"用户需要重新登录");
        }
        //1.2 检验文章的状态
        if (wmNewsDTO.getStatus() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章的状态存在异常");
        }
        //1.3将参数属性拷贝到WmNews属性,判断封面是否自动生成，若自动生成将type的属性值设置为null
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDTO,wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDTO.getType())){
            //防止报异常
            wmNews.setType(null);
        }
         //请求参数中的images为集合，而实体类中image为字符串，用Java的流将集合中所有数据化成一个字符串，中间用,隔开
        List<String> images = wmNewsDTO.getImages();
        if (!CollectionUtils.isEmpty(images)) {
            String imagesString = ImagesListToString(images);
            wmNews.setImages(imagesString);
        }
        wmNews.setUserId(wmUser.getId());
        //2.保存或修改文章草稿
        updateOrSave(wmNews);
        //如果保存的是草稿信息。就不用关关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNews.getStatus())){
            return ResponseResult.okResult();
        }
        //3.设置内容和素材和封面之间的关联关系
           //3.1 将文章内容中的图片列表，抽取出来，存入到map集合中。遍历集合是image就替换前缀存入集合
       List<String> contentImages = parseContentImages(wmNews.getContent());
        if (!CollectionUtils.isEmpty(contentImages)){
            //保存内容和素材的关联关系
            saveContentMaterialRelation(wmUser.getId(),wmNews.getId(),contentImages,WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //保存封面和素材关系
        saveRelativeForCover(contentImages,wmNews,wmNewsDTO);

        // 发送待审核消息   消息内容文章id
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("发送待审核消息成功  消息内容: {}",wmNews.getId());
        return ResponseResult.okResult();
    }

    /*
    * 根据id 查询文章信息
    * */
    @Override
    public ResponseResult<WmNews> findNewsById(Integer id) {
        //参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /*
    * 根据id删除文章信息，若文章上架则不能删除，文章状态为9且已上架
    * */
    @Override
    public ResponseResult<WmNews> deleteNewsById(Integer id) {
        //1.参数校验
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        //2.根据id查询出文章信息
        WmNews wmNews = this.getById(id);
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在");
        }
        //文章状态为9，enable为1不能删除，其它都可以删除
        if (wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章已发布上架不能删除");
        }
        //删除，先删除文章和素材的关联关联关系
        Long articleId = wmNews.getArticleId();
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,articleId));
        //删除文章
        removeById(id);
        return ResponseResult.okResult();
    }

    /*
    * 根据id修改文章信息
    * */
    @Override
    public ResponseResult<WmNews> updateNewsById(WmNews wmNews) {
        //1.校验参数
        if (wmNews ==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //2.修改文章信息
        this.updateById(wmNews);
        return ResponseResult.okResult();
    }

    /*
* 文章的上下架
* */
    @Override
    public ResponseResult<WmNews> upOrDownNews(WmNewsDTO wmNewsDTO) {
        //1.检验参数
        if (wmNewsDTO == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        //1.1
        if (wmNewsDTO.getEnable()==null || !WemediaConstants.WM_NEWS_DOWN.equals(wmNewsDTO.getEnable())&&!WemediaConstants.WM_NEWS_UP.equals(wmNewsDTO.getEnable())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数上下架状态异常");
        }
        //发布的文章才能上下架
        WmNews wmNews = this.getById(wmNewsDTO.getId());
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)){
             return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章未发布不能进行上下架");
        }
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,wmNews.getId()).set(WmNews::getEnable,wmNewsDTO.getEnable()));
        return ResponseResult.okResult();
    }


    @Autowired
    WmNewsMapper wmNewsMapper;
    /*
    * 查询所有文章列表，带作者名称
    * */
    @Override
    public ResponseResult<WmNewsVO> selectAll(NewsAuthDTO newsAuthDTO) {
        //1.检查参数
        newsAuthDTO.checkParam();
        //1.1 获取当前页，和当前页的起始索引
        Integer pageNum = newsAuthDTO.getPage();
        Integer size = newsAuthDTO.getSize();

       //1.2将当前页码改成起始索引,便于后期limit查询
        newsAuthDTO.setPage((newsAuthDTO.getPage()-1)*size);
        //1.3设置标题
        if (StringUtils.isNotBlank(newsAuthDTO.getTitle())){
            newsAuthDTO.setTitle("%"+newsAuthDTO.getTitle()+"%");
        }
        //2.开始查询,查询数据，查询数量
      List<WmNewsVO> wmNewsList =  wmNewsMapper.findAllNewsPage(newsAuthDTO);
       Long total = wmNewsMapper.findCount(newsAuthDTO);



       PageResponseResult result = new PageResponseResult(pageNum,newsAuthDTO.getSize(),total,wmNewsList);
       result.setHost(webSite);
        return result;
    }

    /*
    * 根据id查询文章作者
    * */
    @Override
    public ResponseResult<WmNewsVO> selectOne(Integer id) {
        //1.校验参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        WmNewsVO wmNewsVO= wmNewsMapper.findOneById(id);
        if (wmNewsVO==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(webSite);
        return result;
    }

    /*
    * 人工审核，修改文章状态
    * */
    @Override
    public ResponseResult updateStatus(NewsAuthDTO dto, Short status) {
        //判断是否为人工审核，人工审核状态为3，其它不管
        //1.参数校验
        dto.checkParam();
        if (dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户id为空");
        }

        WmNews byId = this.getById(dto.getId());
        if (byId == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }
        if (byId.getStatus() == 9){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布上线");
        }
        byId.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            byId.setReason(dto.getMsg());
        }
        updateById(byId);
        // TODO 通知定时发布文章
        if(status.shortValue() == WmNews.Status.ADMIN_SUCCESS.getCode()){
            long publishTime = byId.getPublishTime().getTime(); // 发布时间
            long nowTime = System.currentTimeMillis(); // 当前时间
            long remainTime = (publishTime - nowTime);  // 距离发布文章还有多长时间
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , byId.getId()
                    , new MessagePostProcessor() {
                        /**
                         * 消息的后置处理器
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            // 对消息做后置处理 设置消息头 x-delay , 延迟的时间
                            message.getMessageProperties().setHeader("x-delay",remainTime<=0 ? 0 : remainTime);
                            return message;
                        }
                    }
            );
            log.info("文章发布消息");
        }
        return ResponseResult.okResult();
    }


    //保存封面关系
    private void saveRelativeForCover(List<String> contentImages, WmNews wmNews, WmNewsDTO wmNewsDTO) {
        // 1. 拿到前端传递过来的封面集合
        List<String> images = wmNewsDTO.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDTO.getType())) {
            // 需要自动生成封面
            if(contentImages.isEmpty()){ // 如果没有内容图片 设置为 无封面
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if(contentImages.size() > 0 && contentImages.size()<=2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);// 设置单图
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);// 设置多图
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if(!CollectionUtils.isEmpty(images)){
                String s = ImagesListToString(images);
                wmNews.setImages(s);
            }
            updateById(wmNews);// 更新wmNews中 图片类型  及 封面
        }
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
        if(!CollectionUtils.isEmpty(images)){
            // 如果封面不是自动生成，那么获取的是前端传过来的封面集合 是有前缀的  需要替换一下
            images = images.stream().map(url -> url.replaceAll(webSite,"")).distinct().collect(Collectors.toList());
        }
        saveContentMaterialRelation(wmUser.getId(),wmNews.getId(),images,WemediaConstants.WM_IMAGE_REFERENCE);
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

  //内容引用
    private void saveContentMaterialRelation(Integer wmUserId, Integer id, List<String> contentImages, Short wmContentReference) {
      //得到用户所有素材的id

       List<Integer> ids= wmMaterialMapper.selectRelIds(contentImages,wmUserId);
        //判断素材库中用户的素材数量与前台穿的数量大小
        if (CollectionUtils.isEmpty(ids) || ids.size()<contentImages.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"相关素材不存在");
        }
        wmNewsMaterialMapper.saveRelation(ids,id,wmContentReference);
    }

    //将图片素材的路径抽取出来
    private List<String> parseContentImages(String content) {
        //将json格式的字符串转化为集合
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        //挑选出集合中为image的信息
      return   maps.stream().filter(o->WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(o.get("type")))
              .map(o->(String)o.get("value")).map(url->url.replaceAll(webSite,"")).distinct()
              .collect(Collectors.toList());
    }

    //保存或修改
    private void updateOrSave(WmNews wmNews) {
        //默认都是上传
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //文章id为空则为保存文章，否则为修改文章
        if(wmNews.getId() == null){
            this.save(wmNews);
        }else {
            //要想修改文章需要先删除之前的关联，文章与素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    //将集合转化为字符串，多个图片路径之间用,隔开。使用jdk的stream
    private String ImagesListToString(List<String> images) {
       /* //1.创建流
        Stream<String> stream = images.stream();
        //2.中间操作
        String collect = stream.map(url -> url.replaceAll(webSite, "")).collect(Collectors.joining(","));
        return collect;*/
        return images.stream()
                .map(url -> url.replaceAll(webSite,""))
                .collect(Collectors.joining(","));

    }


}
